package com.jacklin.service.Impl;

import com.jacklin.exception.MyException;
import com.jacklin.redis.RedisLock;
import com.jacklin.service.SecondKillService;
import com.jacklin.utils.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 林必昭
 * @Date 2019/4/27 22:18
 */
@Service
public class SecondKillServiceImpl implements SecondKillService {

    private static final int TIMEOUT = 10*1000; //超时时间 10s

    @Autowired
    private RedisLock redisLock;

    /**
     * 秒杀活动，零食特价，限量100000份
     * @param productId
     * @return
     */

    static Map<String,Integer> products;
    static Map<String,Integer> stock;
    static Map<String,String> orders;
    static
    {
        /**
         * 模拟多个表，商品表，库存表，秒杀成功订单表
         */
        products = new HashMap<>();
        stock = new HashMap<>();
        orders = new HashMap<>();
        products.put("123456",100000);
        stock.put("123456",100000);
    }

    private String queryMap(String productId){
        return "秒杀商品 "
                + products.get(productId)
                +"，还剩"+ stock.get(productId) +"份"
                +"，该商品成功下单人数："+ orders.size()+"人";
    }


    @Override
    public String querySecondKillProductInfo(String productId) {
        return this.queryMap(productId);
    }

    /**
     * 模拟不同用户秒杀统一商品的请求
     * @param productId
     */
    @Override
    public void orderProductMockDiffUser(String productId) {

        //加锁
        long time = System.currentTimeMillis()+TIMEOUT;
        if(!redisLock.lock(productId,String.valueOf(time))){
            throw new MyException(101,"人太多，请重新尝试");
        }
        //1.查看该商品的库存，如果为0则活动结束
        Integer stockNum = stock.get(productId);
        if (stockNum==0){
            throw new MyException(100,"商品被抢光了，下次再来");
        }else {
            //2.下单
            orders.put(KeyUtil.randomGeneratingUniqueKey(),productId);
            //3.减库存
            stockNum = stockNum-1;
            try{
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            stock.put(productId,stockNum);
        }
        //解锁
        redisLock.unLock(productId,String.valueOf(time));
    }
}
